class Task {
	constructor(func, resolve, reject) {
		this.func = func;
		this.resolve = resolve;
		this.reject = reject;
	}

	run() {
		this.func().then(this.resolve).catch(this.reject);
	}
}

class SuperTask {
	constructor(parallelCount = 2) {
		this.parallelCount = parallelCount;
		this.queue = [];
		this.running = 0;
	}

	add(taskFunc) {
		return new Promise((resolve, reject) => {
			const task = new Task(taskFunc, resolve, reject);
			this.queue.push(task);
			this.startNextTask();
		});
	}

	startNextTask() {
		if (this.running >= this.parallelCount || this.queue.length === 0) {
			return;
		}

		this.running++;
		const task = this.queue.shift();
		task.run().finally(() => {
			this.running--;
			this.startNextTask(); // 继续执行下一个任务  
		});
	}
}

// Vue 插件部分  
const SuperTaskPlugin = {
	install(Vue, options) {
		Vue.prototype.$superTask = new SuperTask(options.parallelCount || 2);
	}
};

export default SuperTaskPlugin;